<?php

namespace yunj\core\control\form\field;

class Table extends YunjField {

    protected static function defineExtraArgs(): array {
        return [
            'cols' => [],         // 表头配置。如：[['title'=>'表头1','field'=>'key1','verify'=>'require','readonly'=>true],['title'=>'表头2','field'=>'key2']]
            'maxHeight' => '300', // 表格容器的最大高度
            'addAction' => true,  // 添加操作
            'delAction' => true,  // 删除操作
            'sortAction' => true,  // 删除操作
        ];
    }

    protected static function handleArgs(array $args): array {
        // cols
        $cols = $args['cols'];
        $cols = $cols ?: [];
        if ($cols) {
            if (!is_array($cols)) {
                throw new GeneralException('类型[table]配置[cols]格式错误');
            }
            for ($i = 0; $i < count($cols); $i++) {
                $col = $cols[$i];
                if (!is_array($col)) {
                    throw new GeneralException("类型[table]配置[cols][{$i}]格式错误");
                }
                $col += [
                    'title' => '',
                    'field' => '',
                    'width' => '',
                    'verify' => '',
                    'readonly' => false,
                ];
                if (!$col['title']) {
                    throw new GeneralException("类型[table]配置[cols][{$i}][title]不能为空");
                }
                if (!$col['field']) {
                    throw new GeneralException("类型[table]配置[cols][{$i}][field]不能为空");
                }
                if (strstr($col['verify'], 'table')) {
                    throw new GeneralException("类型[table]配置[cols][{$i}][verify]验证规则不能包含table");
                }
                if (!is_bool($col['readonly'])) {
                    throw new GeneralException("类型[table]配置[cols][{$i}][readonly]格式错误");
                }
                $cols[$i] = $col;
            }
            $args["cols"] = $cols;
        }
        // maxHeight
        $maxHeight = $args['maxHeight'];
        if ($maxHeight) {
            $args['maxHeight'] = str_replace('px', '', $maxHeight);
        }
        // verify
        $verify = $args["verify"];
        if (!strstr($verify, 'table')) {
            $args["verify"] .= ($verify ? "|" : "") . "table:" . base64_encode(json_encode($args["cols"], JSON_UNESCAPED_UNICODE));
        }

        return $args;
    }

}